<?php

namespace HelloAdmin\Controller;

use Think\Controller;

class CommonController extends Controller {

    protected $_userId = 0;
    protected $_userInfo = array();
    protected $_needLogin = true;
    protected $_pageTile = '开发测试中';
    protected $_pageKeywords = '开发测试中';
    protected $_pageDescription = '开发测试中';

    protected $offset = 0;
    protected $limit = 18;


    /**
     *
     * @var type
     */
    protected $_url = '';
    private $_getfilter = "'|<[^>]*?>|^\\+\/v(8|9)|\\b(and|or)\\b.+?(>|<|=|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    private $_postfilter = "^\\+\/v(8|9)|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|<\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
    private $cookiefilter = "\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";

    public function __construct() {
        parent::__construct();
        $offset = I('request.offset');
        $limit = I('request.limit');
        $this->offset = empty($offset)?$this->offset:$offset;
        $this->limit = empty($limit)?$this->limit:$limit;
        C('LAYOUT_ON',false);
        C('HTML_CACHE_ON',false);
    }

    public function _initialize(){
        if($this->_needLogin){
            $this->_userId = session('user_id');
            if(empty($this->_userId)) {
                session_destroy();
                $this->redirect('/admin/Public/index', null, 0, '');
                exit();
            }
            $this->_userInfo = session(C('USER_AUTH_KEY'));
        }
    }


    /**
     * 图片上传处理
     * @return type
     */

    public function UploadImg(array $config){
        $configs = array(
                'rootPath' =>  I('server.DOCUMENT_ROOT'), //保存根路径
                'maxSize' => empty($config['maxSize'])?0:$config['maxSize'],
                'savePath' => empty($config['savePath'])?'/Public/Uploads/default/':$config['savePath'],
                'saveName' => empty($config['saveName'])?'':$config['saveName'],
                'exts' => empty($config['exts'])?array('jpg', 'gif', 'png', 'jpeg'):$config['exts'],
                'autoSub' => empty($config['autoSub'])?false:$config['autoSub'], //开启子目录保存
                'subName' => empty($config['subName'])?'getSubName':$config['subName'],
            );
        $upload = new \Think\Upload($configs); // 实例化上传类
        $info = $upload->upload();
        $upload->saveName = 'time';
        if (!$info) {// 上传错误提示错误信息
            \Think\Log::write('UploadImg Error :' .var_export($upload->getError(), 1). var_export($_FILES, 1));
            //p($upload->getError());p($configs);p(file_exists($configs['rootPath']));
        }else {// 上传成功
            foreach($info as $file){
                $targetFile = $file['savepath'].$file['savename'];
            }
            //$image_id = md5(time().getRandStr());
            // $imgs = array(
            //     'image_id' => $image_id,
            //     'storage' => 'file',
            //     'url' => $targetFile,
            //     'last_modified' => time()
            // );
            //D('Common/Image')->SaveData($imgs);
            //\Think\Log::write('upload file  callback info:'.var_export($info,1));
            echo $targetFile;
        }
    }



    /**
     *
     * 发站内信
     * @param mixed $member_id
     * @param string $message 发送内容
     */
    protected function SendMsg($member_id, $message) {
        if (empty($member_id) && empty($message)) {
            return FALSE;
        }

        return Common::SysMsg($member_id, $message);
    }

    /**
     * 邮件群发
     *
     * @param mixed $mailto
     * @param string $subject
     * @param string $body
     * @return boolean
     */
    protected function SendMail($mailto, $subject, $body) {
        //return false;
        if (is_string($mailto)) {
            $mailto = explode(',', $mailto);
        }
        foreach ($mailto as $mail) {
            $this->MailTo($mail, $subject, $body);
        }
    }

    /**
     * 发送邮件
     * @param string $mailto
     * @param string $subject
     * @param string $body
     * @return boolean
     */
    private function MailTo($mailto, $subject, $body) {
        //Thinkphp的导入方式，放在/ThinkPHP/Extend/Vendor/
        //vendor('PHPMailer.class#phpmailer');
        import("Common.Library.Vendor.PHPMailer.class", '', '.phpmailer.php');
        //创建mail对象
        $mail = new PHPMailer();
        $mail->IsSMTP(); //设置使用SMTP服务器发送
        $mail->Host = "smtp.exmail.qq.com";  //设置发件箱的服务器
        $mail->SMTPAuth = true;     // 设置需要验证
        $mail->Username = "regist@uli9.com";  // 发件人使用邮箱
        $mail->Password = 'ww.360.cn'; // 设置发件人密码
        $mail->From = "regist@uli9.com"; // 发件人邮箱
        $mail->FromName = C('SYS_NAME'); //发送者名称
        $mail->AddAddress($mailto); // 添加发送地址
        $mail->IsHTML(true); //指定支持html格式
        $mail->CharSet = "UTF-8";
        $mail->Subject = $subject;
        $mail->Body = $body;
        //dump($mail->Send());exit();
        if ($mail->Send()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送手机短信
     *
     * @param string $number
     * @param string $message
     * @return boolean
     */
    protected function SendSMS($number, $message) {
        if (is_string($number)) {
            $number = explode(',', $number);
        }
        foreach ($number as $val) {
            $this->SMS($val, $message);
        }
    }

    /**
     * 发送手机短信
     *
     * @param string $number
     * @param string $message
     * @return boolean
     */
    private function SMS($number, $message) {
        if (!\Validate::IsCellphone($number) && empty($message)) {
            return FALSE;
        }
        $url = 'http://120.25.202.19:8888/sms.aspx';
        //'http://106.ihuyi.cn/webservice/sms.php?method=Submit';
        $postData = 'action=send&extno=&userid=' . C('SMS_ID') . '&account=' . C('SMS_USER') . '&password=' . C('SMS_PASS');
        $postData .= '&mobile=' . $number . '&content=' . rawurlencode($message);
        //短信发送初始化
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        $return_str = curl_exec($curl);
        curl_close($curl);
        //\Think\Log::write("send message:".var_export($return_str,1));
        preg_match("/<code>(\d+)<\/code>/", $return_str, $pre_arr_num);
        //\Think\Log::write("send message:".var_export($return_str))
        if ($pre_arr_num[1] == '2') {
            return true;
        } else {
            return false;
        } //0提交失败,2提交成功,408同一手机号码一分钟之内发送频率超过10条，系统将冻结你的帐号
    }


    /**
     * 阻止攻击
     * @param type $inputValue
     * @param type $filterReg
     */
    private function _StopAttack($inputValue, $filterReg) {
        if (preg_match("/" . $filterReg . "/is", $inputValue) == 1) {
            echo '<script>document.location.href="' . $this->_url . '"</script>';
            exit();
        }
        return $inputValue;
    }

    /**
     *
     * 过滤输入数据
     *
     * @param mixed $param 参数名：a,b,c或array('a','b','c')
     *
     * @return string array $array array('a'=>1,'b'=>'2','c'=>3);
     */
    public function GetParam($param) {
        $arrVal = '';
        if (empty($param)) {
            return FALSE;
        }
        if (is_string($param)) {
            $param = explode(',', $param);
        }
        $single = FALSE;
        if (count($param) == 1) {
            $single = TRUE;
        }
        foreach ($param as $key) {
            $val = '';
            if (isset($_POST[$key])) {
                $val = $this->_StopAttack($_POST[$key], $this->_postfilter);
            } else if (isset($_GET[$key])) {
                $val = $this->_StopAttack($_GET[$key], $this->_getfilter);
            }

            $arrVal[$key] = \Common\Library\COM\Input::getInstance()->getVar($val);

            if ($single) {
                return $arrVal[$key];
            }
        }

        return $arrVal;
    }


    public function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') {
        $this->assign('pageTitle',$this->_pageTile);
        $this->assign('pageDescription',  $this->_pageDescription);
        $this->assign('pageKeywords',  $this->_pageKeywords);
        $this->assign('userId',  $this->_userId);

        parent::display($templateFile,$charset,$contentType,$content,$prefix);
    }

    public function layerIfreamRe($msg='',$url = '',$type='success'){
        if($type == 'error'){
            $msg = '操作失败';
        }else{
            $msg = empty($msg)?'操作成功':$msg;
        }

        if(empty($url)){
            $dourl = 'location.href=history.go("-1")';
        }else{
            $dourl = 'location.href="'.U($url).'"';
        }
        echo <<<Eof
        <script src="/Public/plugin/gb312/js/jquery.min.js" ></script>
        <script src="/Public/plugin/gb312/js/plugins/layer/layer.min.js" ></script>
        <script src="/Public/plugin/gb312/js/plugins/sweetalert/sweetalert.min.js"></script>
        <link href="/Public/plugin/gb312/css/plugins/sweetalert/sweetalert.css" rel="stylesheet">
        <script>
            $(function(){
                 swal({
                    title:"{$msg}",
                    text:"",
                    type:"{$type}",
                },function(){
                    //当你在iframe页面关闭自身时
                    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                    parent.layer.close(index);
                    {$dourl};
                });
            });
        </script>
Eof;
            exit;
    }


}
